package cn.xlbweb.cli.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @author: bobi
 * @date: 2019-09-16 20:21
 * @description:
 */
@Slf4j
public class CliSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        // 获取token
        String token = WebUtils.toHttp(request).getHeader("ok-token");
        // 获取requestURI
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestURI = httpServletRequest.getRequestURI();
        // 如果未携带token 则默认前后端不分离模式
        if (StringUtils.isBlank(token)) {
            log.info("{}请求未携带token", requestURI);
            return super.getSessionId(request, response);
        }
        // 如果已携带token
        log.info("{}请求已携带token={}", requestURI, token);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "Stateless request");
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        return token;
    }
}
